/**
 * Created by jackliu on 15/12/21.
 */
var express = require('express');
var useragent = require('express-useragent');
var router = express.Router();
var CONFIG = require('../../common/config');
var BASE_IP = CONFIG.BASE_IP;
var URL=require('url');

var ItbDocumentModel = require('../../common/mysql/mapping/ItbDocumentModel');
var ItbBrowseInfoModel = require('../../common/mysql/mapping/ItbBrowseInfoModel');
var ItbRelayInfoModel = require('../../common/mysql/mapping/ItbRelayInfoModel');
var ItbFeedbackModel = require('../../common/mysql/mapping/ItbFeedbackModel');
var CODE = require('../../common/code');
var qiniu = require('qiniu');
var WECHAT = require('../../common/util/wechat');
var ComUtil = require('../../common/util/CommonUtil');
var WX = require('../../common/util/wx');

var rpcFunc=require('../routes/rpcSrv/rpcFunc.js');


/* test. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource from preview');
});
//------------------------------------------------------------------


/* 获取文档的预览图.
 * 方式:GET
 * 参数:pc:1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:docId:文档id
 * 参数:title(可选) 微信分享用
 * 参数:content(可选) 微信分享用
 *
 * 测试地址：http://localhost:3000/preview/pDoc?docId=1
 * */
function pDoc(req, res, next) {
    // 微信认证参数
    var wxCode = req.query.code || req.body.code || null;
    var wxState = req.query.state || req.body.state;

    // 普通参数
    var doc_id = req.body.docId || req.query.docId;
    var title = req.body.title || req.query.title || "一键生成";
    var content = req.body.content || req.query.content || "快来和我们一起‘一键生成’吧！";
    var homeHost = CONFIG.HOME_SERVER_FULL_URL;


    // 转发到home服务器
    var shareUrl = homeHost+'/preview/pDoc?docId='+doc_id+'&title='+title+'&content='+content;
    return res.redirect(shareUrl);


    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;
    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
        return res.render('error', { message: CODE.DOC_ID_EMPTY });
    }

    var entity = new ItbDocumentModel({
        doc_id: doc_id,
        del_flg: 0
    });
    entity.findFromDB(function(error, ret){
        if (error) {
            return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: error} });
        }

        if (ret == null || ret.length == 0) {
            return res.render('error', { message: '文档不存在！' });
        }

        var wxApi = WX.getWxWeb().getWxApi();
        var wxOauth = WX.getWxWeb().getWxOAuth();
        if (ret[0].track && ret[0].track == 1) {
            // 进行数据统计
            var shareUrl = apiHost+'/preview/pDoc?docId='+doc_id+'&title='+title+'&content='+content;
            var aUrl= wxOauth.getAuthorizeURL(shareUrl,'STATE','snsapi_userinfo');
            if (wxCode == null) {
                // 跳转到微信授权页面
                return res.redirect(aUrl);
            } else {
                // 微信认证
                wxOauth.getAccessToken(wxCode, function (err, result) {
                    if (err) {
                        return res.render('error', { message: CODE.WX_USER_OAUTH_ERR});
                    }

                    var accessToken = result.data.access_token;
                    var openid = result.data.openid;

                    // 获取用户信息
                    wxOauth.getUser(openid, function (err, result) {
                        if (err){
                            return res.render('error', { message: "未登记用户！"});
                        }

                        var userInfo = result;

                        // 创建访问数据
                        var newEnt = new ItbBrowseInfoModel({
                            doc_id : doc_id,
                            open_id  : userInfo.openid,
                            union_id : userInfo.unionid||'',
                            visit_mode: 1,// pDoc方式
                            nickname : userInfo.nickname,
                            sex : userInfo.sex,
                            city : userInfo.city,
                            country : userInfo.country,
                            province : userInfo.province,
                            language :  userInfo.language || '',
                            headimgurl : userInfo.headimgurl || '',
                            remark : userInfo.remark || '',
                            privilege : JSON.stringify(userInfo.privilege || [])
                        });
                        newEnt.saveToDB(function(err, newVisitId){
                            if(err){
                                return res.render('error', { message: "访问错误！"});
                            }

                            // 主proc
                            entity.getPagesInfoByDocId(function(err, items){
                                if (err) {
                                    return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: err} });
                                }

                                var data = items;
                                if (data == null || data.length == 0) {
                                    data = [{doc_name:'空白文档',thumb_s:'',page_index:-1}];
                                }

                                var info = {
                                    doc_name: data[0].doc_name,
                                    pages: data,
                                    platform: platform,
                                    api_host: apiHost,
                                };

                                var myParam = {
                                    pImg: apiHost + '/preview/_itb.gif?k='+newVisitId,
                                    ui: userInfo.unionid||'',
                                    di: doc_id
                                };
                                info.myParam = JSON.stringify(myParam);

                                // 微信js-sdk授权
                                var param = {
                                    debug: false,
                                    jsApiList: [
                                        'onMenuShareTimeline',
                                        'onMenuShareAppMessage'
                                    ],
                                    url: apiHost + req.originalUrl
                                };
                                wxApi.getJsConfig(param, function(err2,ret){
                                    if (!err2) {
                                        ret.title = title + "（长图展示）";
                                        ret.desc = content;
                                        ret.link = aUrl;

                                        info.wechat = JSON.stringify(ret);
                                    }
                                    return res.render('indexDoc', info);
                                });
                            });

                        });// newEnt.saveToDB
                    });// wxOauth.getUser
                });
            }

        } else {
            // 普通浏览
            entity.getPagesInfoByDocId(function(err, results){
                if (err) {
                    return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: err} });
                }

                var data = results;
                if (data == null || data.length == 0) {
                    data = [{doc_name:'空白文档',thumb_s:'',page_index:-1,track:0}];
                }

                var info = {
                    doc_name: data[0].doc_name,
                    pages: data,
                    platform: platform,
                    api_host: apiHost,
                    myParam: JSON.stringify({})
                };

                // 微信js-sdk授权
                var param = {
                    debug: false,
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                    ],
                    url: apiHost + req.originalUrl
                };
                wxApi.getJsConfig(param, function(err2,ret){
                    if (!err2) {
                        ret.title = title + "（长图展示）";
                        ret.desc = content;
                        ret.link = apiHost + req.originalUrl;

                        info.wechat = JSON.stringify(ret);
                    }
                    return res.render('indexDoc', info);
                });

                // 不进行数据统计
                //var reqUrl = apiHost + req.originalUrl;
                //WECHAT.getSignature(reqUrl,function(err2, ret){
                //    if (!err2) {
                //        ret.title = title;
                //        ret.desc = content;
                //        ret.link = reqUrl;
                //
                //        info.wechat = JSON.stringify(ret);
                //    }
                //    return res.render('indexDoc', info);
                //});
            });
        }
    });
}
router.get('/pDoc', pDoc);
router.post('/pDoc', pDoc);
//------------------------------------------------------------------


/* 播放文档预览.
 * 方式:GET
 * 参数:pc: 1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:docId: 文档id
 * 参数:flg: 0不加载媒体,1加载媒体
 * 参数:tFlg: 0普通用,1贺卡用
 * 参数:title(可选) 微信分享用
 * 参数:content(可选) 微信分享用
 * */
function dispDoc(req, res, next) {
    var doc_id = req.body.docId || req.query.docId;
    var mediaFlg = Number(req.body.flg || req.query.flg || "0");
    var typeFlg = req.body.tFlg || req.query.tFlg || "0";
    var title = (req.body.title || req.query.title || "一键生成") + ((mediaFlg=="1")?"（多媒体播放）":"（图文播放）");
    var content = req.body.content || req.query.content || "快来和我们一起‘一键生成’吧！";

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var pos = 3;// 1:左上,2:右上,3:右下,4:左下,5:中心
    if (Number(typeFlg) == 1){
        pos = 5;
    }

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
        return res.render('error', { message: CODE.DOC_ID_EMPTY });
    }

    var entity = new ItbDocumentModel({
        doc_id: doc_id,
        del_flg: 0
    });
    entity.getPagesInfoByDocId(function(err, results){
        if (err) {
            return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: err} });
        }

        var bHasMedia = false;
        var data = results;
        var jsonData = [];
        if (data == null || data.length == 0) {
            data = [{doc_name:'空白文档',thumb_s:'',page_index:-1}];
        } else {
            for (i in data){
                var jsonItem = {
                    audio:JSON.parse(data[i].audio)||[],
                    video:JSON.parse(data[i].video)||[]
                }
                jsonData.push(jsonItem);

                if (!bHasMedia){
                    if ((jsonItem.audio && jsonItem.audio.length>0) ||
                        (jsonItem.video && jsonItem.video.length>0)) {
                        bHasMedia = true;
                    }
                }
            }
        }

        if (mediaFlg == 1 && !bHasMedia) {
            mediaFlg = 0;
        }

        var info = {
            doc_name: data[0].doc_name,
            pages: data,
            pagesJson: jsonData,
            pagesJsonStr: JSON.stringify(jsonData),
            platform: platform,
            typeFlg: typeFlg,
            mediaFlg: mediaFlg,
            mediaPos: pos,
            api_host: apiHost,
        };

        var reqUrl = apiHost + req.originalUrl;
        WECHAT.getSignature(reqUrl,function(err2, ret){
            if (!err2) {
                ret.title = title;
                ret.desc = content;

                info.wechat = JSON.stringify(ret);
            }
            res.render('displayDoc', info);
        });

    });

}
router.get('/dispDoc', dispDoc);
router.post('/dispDoc', dispDoc);
//------------------------------------------------------------------


/* 播放文档预览.
 * 方式:GET
 * 参数:pc: 1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:docId: 文档id
 * 参数:flg: 0不加载媒体,1加载媒体
 * 参数:tFlg: 0普通用,1贺卡用
 * 参数:title(可选) 微信分享用
 * 参数:content(可选) 微信分享用
 * */
function dispDoc2(req, res, next) {
    // 微信认证参数
    var wxCode = req.query.code || req.body.code || null;
    var wxState = req.query.state || req.body.state;

    // 普通参数
    var doc_id = req.body.docId || req.query.docId;
    var mediaFlg = Number(req.body.flg || req.query.flg || "0");
    var typeFlg = Number(req.body.tFlg || req.query.tFlg || "0");
    var title = req.body.title || req.query.title || "一键生成";
    var content = req.body.content || req.query.content || "快来和我们一起‘一键生成’吧！";
    var surfix = (mediaFlg==1)?"（多媒体播放）":"（图文播放）";

    var homeHost = CONFIG.HOME_SERVER_FULL_URL;


    // 转发到home服务器
    var shareUrl = homeHost + '/preview/dispDoc2?docId=' + doc_id +
        '&flg=' + mediaFlg + '&tFlg=' + typeFlg +
        '&title=' + title + '&content=' + content;
    return res.redirect(shareUrl);


    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var pos = 3;// 1:左上,2:右上,3:右下,4:左下,5:中心
    if (Number(typeFlg) == 1){
        pos = 5;
    }

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    if(typeof doc_id=='undefined' || doc_id == null || doc_id.trim().length == 0){
        return res.render('error', { message: CODE.DOC_ID_EMPTY });
    }

    // Check track
    var entity = new ItbDocumentModel({
        doc_id: doc_id,
        del_flg: 0
    });
    entity.findFromDB(function(error, ret) {
        if (error) {
            return res.render('error', {message: CODE.OPERATION_FAILED, error: {stack: error}});
        }

        if (ret == null || ret.length == 0) {
            return res.render('error', {message: '文档不存在！'});
        }

        var wxApi = WX.getWxWeb().getWxApi();
        var wxOauth = WX.getWxWeb().getWxOAuth();
        if (ret[0].track && ret[0].track == 1) {
            // 进行数据统计
            var shareUrl = apiHost + '/preview/dispDoc2?docId=' + doc_id +
                '&flg=' + mediaFlg + '&tFlg=' + typeFlg +
                '&title=' + title + '&content=' + content;
            var aUrl = wxOauth.getAuthorizeURL(shareUrl, 'STATE', 'snsapi_userinfo');
            if (wxCode == null) {
                // 跳转到微信授权页面
                return res.redirect(aUrl);
            } else {
                // 微信认证
                wxOauth.getAccessToken(wxCode, function (err, result) {
                    if (err) {
                        return res.render('error', { message: CODE.WX_USER_OAUTH_ERR});
                    }

                    var accessToken = result.data.access_token;
                    var openid = result.data.openid;

                    // 获取用户信息
                    wxOauth.getUser(openid, function (err, result) {
                        if (err){
                            return res.render('error', { message: "未登记用户！"});
                        }

                        var userInfo = result;

                        // 创建访问数据
                        var newEnt = new ItbBrowseInfoModel({
                            doc_id : doc_id,
                            open_id  : userInfo.openid,
                            union_id : userInfo.unionid||'',
                            visit_mode: (mediaFlg==1)?3:2,// dispDoc方式
                            nickname : userInfo.nickname,
                            sex : userInfo.sex,
                            city : userInfo.city,
                            country : userInfo.country,
                            province : userInfo.province,
                            language :  userInfo.language || '',
                            headimgurl : userInfo.headimgurl || '',
                            remark : userInfo.remark || '',
                            privilege : JSON.stringify(userInfo.privilege || [])
                        });
                        newEnt.saveToDB(function(err, newVisitId){
                            if(err){
                                return res.render('error', { message: "访问错误！"});
                            }

                            // 主proc
                            entity.getPagesInfoByDocId(function(err, results){
                                if (err) {
                                    return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: err} });
                                }

                                var bHasMedia = false;
                                var data = results;
                                var jsonData = [];
                                if (data == null || data.length == 0) {
                                    data = [{doc_name:'空白文档',thumb_s:'',page_index:-1}];
                                } else {
                                    for (i in data){
                                        var jsonItem = {
                                            audio:JSON.parse(data[i].audio)||[],
                                            video:JSON.parse(data[i].video)||[],
                                            thumb:data[i].thumb_s
                                        }
                                        jsonData.push(jsonItem);

                                        if (!bHasMedia){
                                            if ((jsonItem.audio && jsonItem.audio.length>0) ||
                                                (jsonItem.video && jsonItem.video.length>0)) {
                                                bHasMedia = true;
                                            }
                                        }
                                    }
                                }

                                if (mediaFlg == 1 && !bHasMedia) {
                                    mediaFlg = 0;
                                }

                                var info = {
                                    doc_name: data[0].doc_name,
                                    pages: data,
                                    pagesJson: jsonData,
                                    pagesJsonStr: JSON.stringify(jsonData),
                                    platform: platform,
                                    typeFlg: typeFlg,
                                    mediaFlg: mediaFlg,
                                    mediaPos: pos,
                                    api_host: apiHost,
                                };
                                var myParam = {
                                    pImg: apiHost + '/preview/_itb.gif?k='+newVisitId,
                                    ui: userInfo.unionid||'',
                                    di: doc_id
                                };
                                info.myParam = JSON.stringify(myParam);

                                // 微信js-sdk授权
                                var param = {
                                    debug: false,
                                    jsApiList: [
                                        'onMenuShareTimeline',
                                        'onMenuShareAppMessage'
                                    ],
                                    url: apiHost + req.originalUrl
                                };
                                wxApi.getJsConfig(param, function(err2,ret){
                                    if (!err2) {
                                        ret.title = title + surfix;
                                        ret.desc = content;
                                        ret.link = aUrl;

                                        info.wechat = JSON.stringify(ret);
                                    }
                                    return res.render('displayDoc2', info);
                                });
                            });

                        });// newEnt.saveToDB
                    });// wxOauth.getUser
                });
            }

        } else {
            // 普通浏览
            entity.getPagesInfoByDocId(function(err, results){
                if (err) {
                    return res.render('error', { message: CODE.OPERATION_FAILED, error:{stack: err} });
                }

                var bHasMedia = false;
                var data = results;
                var jsonData = [];
                if (data == null || data.length == 0) {
                    data = [{doc_name:'空白文档',thumb_s:'',page_index:-1}];
                } else {
                    for (i in data){
                        var jsonItem = {
                            audio:JSON.parse(data[i].audio)||[],
                            video:JSON.parse(data[i].video)||[],
                            thumb:data[i].thumb_s
                        }
                        jsonData.push(jsonItem);

                        if (!bHasMedia){
                            if ((jsonItem.audio && jsonItem.audio.length>0) ||
                                (jsonItem.video && jsonItem.video.length>0)) {
                                bHasMedia = true;
                            }
                        }
                    }
                }

                if (mediaFlg == 1 && !bHasMedia) {
                    mediaFlg = 0;
                }

                var info = {
                    doc_name: data[0].doc_name,
                    pages: data,
                    pagesJson: jsonData,
                    pagesJsonStr: JSON.stringify(jsonData),
                    platform: platform,
                    typeFlg: typeFlg,
                    mediaFlg: mediaFlg,
                    mediaPos: pos,
                    api_host: apiHost,
                    myParam: JSON.stringify({})
                };

                // 微信js-sdk授权
                var param = {
                    debug: false,
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage'
                    ],
                    url: apiHost + req.originalUrl
                };
                wxApi.getJsConfig(param, function(err2,ret){
                    if (!err2) {
                        ret.title = title + surfix;
                        ret.desc = content;
                        ret.link = apiHost + req.originalUrl;

                        info.wechat = JSON.stringify(ret);
                    }
                    return res.render('displayDoc2', info);
                });

                //var reqUrl = apiHost + req.originalUrl;
                //WECHAT.getSignature(reqUrl,function(err2, ret){
                //    if (!err2) {
                //        ret.title = title;
                //        ret.desc = content;
                //
                //        info.wechat = JSON.stringify(ret);
                //    }
                //    res.render('displayDoc2', info);
                //});

            });
        }
    });

}
router.get('/dispDoc2', dispDoc2);
router.post('/dispDoc2', dispDoc2);
//------------------------------------------------------------------


/* 制作贺卡
 * 方式:GET
 * 参数:pc: 1表示从pc来的请求/为空或者其它值表示从手机来的请求
 * 参数:docId: 文档id
 * 参数:flg: 0不加载媒体,1加载媒体
 * */
qiniu.conf.ACCESS_KEY = 'qBaIavtWjRjUYzTfDYm-Lm9jRAWFBTnnzZrl0zSR';
qiniu.conf.SECRET_KEY = 'dRVZbaztjuWUUfjwTF8gnLu1cgJZ3lVNAaM7jmR3';
qn_domain = 'http://7xogoq.com1.z0.glb.clouddn.com';
qn_bucket = 'itbour-image';
function makeCard(req, res, next) {
    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var doc_id = req.body.docId || req.query.docId;
    var flg = req.body.flg || req.query.flg || "0";

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    // get qiniu upload token
    // 文件名: [(type)/("U"+userId/"T"+random)/(YYYYMMDDhhmmss)/(hash)]
    // type: 0图片，1音频，2视频
    var type = "2";
    var id = "T"+Math.floor(Math.random()*1000000);// userId不存在时
    var tmpNm = "/$(year)$(mon)$(day)$(hour)$(min)$(sec)/$(etag)";

    var putPolicyObj = {};
    putPolicyObj.scope = qn_bucket;
    putPolicyObj.insertOnly = 1; // 仅能以新增模式上传文件
    putPolicyObj.saveKey = "video/"+id+tmpNm;
    putPolicyObj.mimeLimit = "video/*";// 只允许上传视频类型
    putPolicyObj.expires = 3600;

    var putPolicy = new qiniu.rs.PutPolicy2(putPolicyObj);

    gInfo = {
        api_host: 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT,
        qn_domain: 'http://7xogoq.com1.z0.glb.clouddn.com',
        qn_token: putPolicy.token()// token字符串
    };
    var info = {
        platform: platform,
        gInfo: JSON.stringify(gInfo)
    };

    var reqUrl = apiHost + req.originalUrl;
    WECHAT.getSignature(reqUrl,function(err, ret){
        if (!err) {
            info.wechat = JSON.stringify(ret);
        }
        res.render('makeCard', info);
    });

}
router.get('/makeCard', makeCard);
router.post('/makeCard', makeCard);
//------------------------------------------------------------------


/* 抽签
 * 方式:GET
 * */
function drawlots(req, res, next) {
    //var reqUrl = URL.parse(req.url);
    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    var gInfo = {
        api_host: apiHost
    };
    var info = {
        platform: platform,
        gInfo: JSON.stringify(gInfo)
    };

    var reqUrl = apiHost + req.originalUrl;
    WECHAT.getSignature(reqUrl,function(err, ret){
        if (!err) {
            info.wechat = JSON.stringify(ret);
        }
        res.render('drawlots', info);
    });

}
router.get('/drawlots', drawlots);
router.post('/drawlots', drawlots);
//------------------------------------------------------------------
/* （随机）获取签文
 * 方式:GET
 * */
function getDrawlotsItem(req, res, next) {
    var type = req.body.type || req.query.type || "0";//0:随机 1:爱情 2:财运 3:健康 4:事业

    var arrItems = CONFIG.ARR_DRAWLOTS_ITEMS;
    var typeNm = CONFIG.ARR_DRAWLOTS_TYPE;

    var typeIndex =  Number(type);// 1~4
    if (typeIndex >= arrItems.length || typeIndex == 0){// 随机分类
        typeIndex = Math.floor(Math.random()*(arrItems.length-1)) + 1;
    }

    var items = arrItems[typeIndex];
    var itemIndex = Math.floor(Math.random()*items.length);// 随机签文

    var ret = {
        success:1,
        msg:'success',
        data:{
            type:typeIndex,
            typeName:typeNm[typeIndex],
            item:itemIndex,
            itemName:items[itemIndex]
        }
    };
    res.set('Content-Type', 'application/json');
    res.json(ret);
}
router.get('/getDrawlotsItem', getDrawlotsItem);
router.post('/getDrawlotsItem', getDrawlotsItem);
//------------------------------------------------------------------


/* 抽签
 * 方式:GET
 * */
function showDrawlotsItem(req, res, next) {

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var typeIndex = Number(req.body.type || req.query.type || "1");
    var itemIndex = Number(req.body.item || req.query.item || "0");
    var typeNm = CONFIG.ARR_DRAWLOTS_TYPE[typeIndex];
    var itemNm = CONFIG.ARR_DRAWLOTS_ITEMS[typeIndex][itemIndex];

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    gInfo = {
        api_host: apiHost
    };
    var info = {
        platform: platform,
        type: typeIndex,
        itemImg: typeNm+'/'+itemNm+'.jpg',
        gInfo: JSON.stringify(gInfo)
    };

    //var reqUrl = apiHost+'/preview/showDrawlotsItem?type='+typeIndex+'&item='+itemIndex;
    var reqUrl = apiHost + req.originalUrl;
    WECHAT.getSignature(reqUrl,function(err, ret){
        if (!err) {
            info.wechat = JSON.stringify(ret);
        }
        res.render('showDrawlots', info);
    });
}
router.get('/showDrawlotsItem', showDrawlotsItem);
router.post('/showDrawlotsItem', showDrawlotsItem);
//------------------------------------------------------------------


/* 娱乐
 * 方式:GET
 * */
function playGame(req, res, next) {

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var typeIndex = Number(req.body.type || req.query.type || "0");

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    gInfo = {
        api_host: apiHost
    };
    var info = {
        platform: platform,
        type: typeIndex,
        gInfo: JSON.stringify(gInfo)
    };

    var reqUrl = apiHost + req.originalUrl;
    WECHAT.getSignature(reqUrl,function(err, ret){
        if (!err) {
            ret.title = "";// TODO
            ret.desc = "";// TODO

            info.wechat = JSON.stringify(ret);
        }
        res.render('playGame', info);
    });
}
router.get('/playGame', playGame);
router.post('/playGame', playGame);
//------------------------------------------------------------------

/* 加国旗📈图标页面
 * 方式:GET
 * */
function addFlag(req, res, next) {
    var imgUrl = req.body.url || req.query.url || "";// 图片地址

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }


    var info = {
        platform: platform,
        imgUrl: imgUrl,
        uId: -161001,// 16年国庆
    };

    var reqUrl = apiHost + req.originalUrl;
    //WECHAT.getSignature(reqUrl,function(err, ret){
    //    if (!err) {
    //        ret.title = "";// TODO
    //        ret.desc = "";// TODO
    //
    //        info.wechat = JSON.stringify(ret);
    //    }
        res.render('addFlag', info);
    //});
}
router.get('/addFlag', addFlag);
router.post('/addFlag', addFlag);
//------------------------------------------------------------------

/* （随机）加国旗📈图标
 * 方式:GET
 * */
function addFlagProc(req, res, next) {
    var imgUrl = req.body.url || req.query.url || "";// 图片地址

    // 图标地址列表
    var arrIcon = [
        //"http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13/2016/09/30/165104879_WZAHLlKcpPYfJIhD9I62",
        "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13/2016/09/30/200339701_MmAXV4BUNRC6d9wJROdO"
    ];

    // 随机选择
    var icon = arrIcon[Math.floor(Math.random()*arrIcon.length)];

    var tmpUserId = '-161001';// 2016年国庆
    if(imgUrl && imgUrl.length>0) {
        rpcFunc.combineImage(imgUrl,600,icon,200,tmpUserId, function (err,retUrl) {
            if (err) {
                return ret_func(0, '生成失败');
            }
            return ret_func(1,'ok',{url:retUrl});
        });

    } else {
        return ret_func(0,'请先选择图片')
    }

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }
}
router.get('/addFlagProc', addFlagProc);
router.post('/addFlagProc', addFlagProc);
//------------------------------------------------------------------

/* 显示生成结果
 * 方式:GET
 * */
function viewFlag(req, res, next) {
    var imgUrl = req.body.rUrl || req.query.rUrl || "";// 图片地址
    var orgUrl = req.body.oUrl || req.query.oUrl || "";

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }


    imgUrl = 'http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U-161001'+imgUrl;
    var info = {
        platform: platform,
        rUrl: imgUrl,
        oUrl: orgUrl,
        uId: -161001,// 16年国庆
    };

    var reqUrl = apiHost + req.originalUrl;
    //WECHAT.getSignature(reqUrl,function(err, ret){
    //    if (!err) {
    //        ret.title = "";// TODO
    //        ret.desc = "";// TODO
    //
    //        info.wechat = JSON.stringify(ret);
    //    }
    res.render('viewFlag', info);
    //});
}
router.get('/viewFlag', viewFlag);
router.post('/viewFlag', viewFlag);
//------------------------------------------------------------------

/* 2016.10找茬活动
 * 方式:GET
 * */
function nitpick(req, res, next) {

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    var userAgent = req.headers['user-agent'];
    console.log("USER AGENT: "+userAgent);
    var ua = useragent.parse(userAgent);
    var platform = "mobile";
    if (ua.isDesktop){
        platform = "desktop";
    }

    var info = {
        platform: platform,
        uId: -161022,// 2016.10.22
    };

    var reqUrl = apiHost + req.originalUrl;
    //WECHAT.getSignature(reqUrl,function(err, ret){
    //    if (!err) {
    //        ret.title = "";// TODO
    //        ret.desc = "";// TODO
    //        info.wechat = JSON.stringify(ret);
    //    }
    res.render('nitpick', info);
    //});
}
router.get('/nitpick', nitpick);
router.post('/nitpick', nitpick);

// 记录反馈建议
function nitpickProc(req, res, next) {
    var advice = req.body.advice || req.query.advice || "";// 建议
    var tel = Number(req.body.tel || req.query.tel || "0");// 手机号

    var apiHost = 'http://'+CONFIG.API_SERVER_DOMAIN+':'+CONFIG.API_SERVER_PORT;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success:success,
            msg:msg,
            data:data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var entity = new ItbFeedbackModel({
        advice: advice,
        mobile: tel,
        user_id: -161022,// 临时id: 2016/10/22活动
        from: 'event_161022',
    });
    entity.saveToDB(function(error, id){
        // process error
        if(error){
            console.log('preview.js [nitpickProc] Ins Err: '+error);
            return ret_func(0,CODE.OPERATION_FAILED);
        }
        // process success
        return ret_func(1,CODE.OPERATION_SUCCESS,{id:id});
    });
}
router.get('/nitpickProc', nitpickProc);
router.post('/nitpickProc', nitpickProc);

// 提交完毕
function nitpickOK(req, res, next){
    //
    res.render('nitpickOK', {});
}
router.get('/nitpickOK', nitpickOK);
router.post('/nitpickOK', nitpickOK);
//------------------------------------------------------------------

/* 统计用户访问页面的信息.
 * 方式:GET
 * 参数 k: DB数据Id
 * 参数 oi: 用户openId
 * 参数 ui: 用户unionId
 * 参数 di: 文档Id
 * 参数 vm: 访问方式(1:pDoc, 2:dispDoc, ...)
 * 参数 st: 发送时间
 * 参数 n: 1:首次更新(更新start_time和last_time), 0:只更新last_time
 *
 * 测试地址：http://localhost:2000/_itb.gif?u=xxx&d=xxx
 * */
function itbGif(req, res, next) {
    // 一般参数
    var key = Number(req.body.k || req.query.k || '-1');
    var openid = req.body.oi || req.query.oi || '';
    var unionid = req.body.ui || req.query.ui || '';
    var docid = req.body.di || req.query.di || '';
    var mode = Number(req.body.vm || req.query.vm || '0');
    var sendtime = Number(req.body.st || req.query.st || '0');
    var newFlg = Number(req.body.n || req.query.n || '0');

    //res.set({
    //  'Content-Type': 'image/gif',
    //  'Pragma': 'no-cache',
    //  'Cache-Control': 'no-cache, max-age=0, must-revalidate',
    //  'Expires': 'Fri, 01 Jan 1980 00:00:00 GMT'
    //});
    res.sendStatus(204);

    if(key > 0 && sendtime > 0){
        // 更新用户数据
        var entity = null;
        if (newFlg == 1) {
            entity = new ItbBrowseInfoModel({
                id : key,
                open_id  : openid,
                union_id : unionid,
                doc_id : docid,
                visit_mode: mode,
                start_time: sendtime,
                last_time: sendtime
            });

        } else {
            entity = new ItbBrowseInfoModel({
                id : key,
                open_id  : openid,
                union_id : unionid,
                doc_id : docid,
                visit_mode: mode,
                last_time: sendtime
            });
        }

        entity.updateTimeById(function(err, ret){
            console.log('[itbGif] update visit info: '+ err?err:'OK');
        });
    }

}
router.get('/_itb.gif', itbGif);
router.post('/_itb.gif', itbGif);
//------------------------------------------------------------------

/**
 * 更新分享转发信息
 * 参数di: docId
 * 参数ui: unionId
 * 参数rm: relay_mode
 * 参数vm: visit_mode
 */
function updShareInfo(req, res, next) {

    var docId = req.body.di || req.query.di || null;
    var unionId = req.body.ui || req.query.ui || '0';
    var relayMode = Number(req.body.rm || req.query.rm || '0');
    var visitMode = Number(req.body.vm || req.query.vm || '0');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    if (docId == null) {
        return ret_func(0,CODE.OPERATION_FAILED);
    }

    // 创建访问数据
    var newEnt = new ItbRelayInfoModel({
        doc_id : docId,
        union_id  : unionId,
        visit_mode: visitMode,
        relay_mode : relayMode,
    });
    newEnt.saveToDB(function(err, newId) {
        if (err) {
            return ret_func(0,CODE.OPERATION_FAILED);
        } else {
            return ret_func(1,CODE.OPERATION_SUCCESS,newId);
        }
    });
}
router.get('/usi', updShareInfo);
router.post('/usi', updShareInfo);
//------------------------------------------------------------------

module.exports = router;